import axios from 'axios';
import {Loading} from 'element-ui';
import Cookies from 'js-cookie';
import qs from 'qs'
import router from '../router/index';

var instance = axios.create({
  baseURL: ''
});

const ajax = {
  get: function (url, params = {}) {
    let loadingInstance = Loading.service({
      text: '拼命加载中',
      target: document.querySelector('.loadingtext'),
      background: 'rgba(0, 0, 0, 0.4)',
      spinner: 'el-icon-loading',
      lock: true
    })
    instance.defaults.headers.common['token'] = Cookies.get('crmtoken');
    return new Promise((resolve, reject) => {
      instance.get(url, {
        params: params
      })
        .then((response) => {
          if (response.data.code === 0) {
            loadingInstance.close();
            resolve(response.data);
          } else {
            loadingInstance.close();
            resolve(response.data);
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((error) => {
          console.log(error);
          loadingInstance.close();
          if (error.response.status === 798) {
            this.$message.error('登录信息过期，请重新登录');
            router.push({
              path: '/login'
            });
          } else {
            this.$message.error('网络状况不佳,请稍后重试');
          }
        });
      loadingInstance.close();
    });
  },
  post: function (url, data = {}, isformdata, vue) {
    let loadingInstance = Loading.service({
      text: '拼命加载中',
      target: document.querySelector('.loadingtext'),
      background: 'rgba(0, 0, 0, 0.4)',
      spinner: 'el-icon-loading',
      lock: true
    })
    if (vue) {
      vue.btnloading = true;
    }
    if (isformdata) {
      data = qs.stringify(data)
    }
    instance.defaults.headers.common['token'] = Cookies.get('crmtoken');
    return new Promise((resolve, reject) => {
      instance.post(url, data)
        .then((response) => {
          if (vue) {
            vue.btnloading = false;
          }
          if (response.data.code) {
            loadingInstance.close();
            resolve(response.data);
          } else {
            loadingInstance.close();
            resolve(response.data);
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((error) => {
          console.log(error);
          loadingInstance.close();
          if (error.response.status === 798) {
            this.$message.error('登录信息过期，请重新登录');
            router.push({
              path: '/login'
            });
          } else {
            this.$message.error('网络状况不佳,请稍后重试');
          }
        });
      loadingInstance.close();
    });
  },


  pcget: function (url, params = {}) {
    let loadingInstance = Loading.service({
      text: '拼命加载中',
      target: document.querySelector('.loadingtext'),
      background: 'rgba(0, 0, 0, 0.4)',
      spinner: 'el-icon-loading',
      lock: true
    })
    instance.defaults.headers.common['token'] = Cookies.get('crmsupertoken');
    return new Promise((resolve, reject) => {
      instance.get(url, {
        params: params
      })
        .then((response) => {
          if (response.data.code === 0) {
            loadingInstance.close();
            resolve(response.data);
          } else {
            loadingInstance.close();
            resolve(response.data);
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((error) => {
          loadingInstance.close();
          if (error.response.status === 798) {
            this.$message.error('登录信息过期，请重新登录');
            router.push({
              path: '/login'
            });
          } else {
            this.$message.error('网络状况不佳,请稍后重试');
          }
        });
      loadingInstance.close();
    });
  },
  pcpost: function (url, data = {}, isformdata) {
    let loadingInstance = Loading.service({
      text: '拼命加载中',
      target: document.querySelector('.loadingtext'),
      background: 'rgba(0, 0, 0, 0.4)',
      spinner: 'el-icon-loading',
      lock: true
    })
    if (isformdata) {
      data = qs.stringify(data)
    }
    instance.defaults.headers.common['token'] = Cookies.get('crmsupertoken');
    return new Promise((resolve, reject) => {
      instance.post(url, data)
        .then((response) => {
          if (response.data.code) {
            loadingInstance.close();
            resolve(response.data);
          } else {
            loadingInstance.close();
            resolve(response.data);
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((error) => {
          loadingInstance.close();
          if (error.response.status === 798) {
            this.$message.error('登录信息过期，请重新登录');
            router.push({
              path: '/login'
            });
          } else {
            this.$message.error('网络状况不佳,请稍后重试');
          }
        });
      loadingInstance.close();
    });
  },


  downloadpost: function (url, data = {}, isformdata) {
    let loadingInstance = Loading.service({
      text: '拼命加载中',
      target: document.querySelector('.loadingtext'),
      background: 'rgba(0, 0, 0, 0.4)',
      spinner: 'el-icon-loading',
      lock: true
    })
    if (isformdata) {
      data = qs.stringify(data)
    }
    axios({
      method: 'post',// 设置请求方式
      url: url,// 设置请求地址
      data: data, //参数
      headers: {// 设置请求头
        token: Cookies.get('crmtoken')
      }, responseType: 'blob'// 设置相应数据的类型，设置后后台返回的数据会被强制转为blob类型；如果后台返回代表失败的data，前端也无法得知，依然会下载得到名为undefined的文件。
    }).then(function (res) {
      // 得到请求到的数据后，对数据进行处理
      let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'});// 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
      let fileName = decodeURI(res.headers['content-disposition']);// 设置文件名称,decodeURI：可以对后端使用encodeURI() 函数编码过的 URI 进行解码。encodeURI() 是后端为了解决中文乱码问题
      if (fileName) {// 根据后端返回的数据处理文件名称
        fileName = fileName.substring(fileName.indexOf('=') + 1);
      }
      const elink = document.createElement('a')// 创建一个a标签
      elink.download = fileName;// 设置a标签的下载属性
      elink.style.display = 'none';// 将a标签设置为隐藏
      elink.href = URL.createObjectURL(blob);// 把之前处理好的地址赋给a标签的href
      document.body.appendChild(elink);// 将a标签添加到body中
      elink.click();// 执行a标签的点击方法
      URL.revokeObjectURL(elink.href) // 下载完成释放URL 对象
      document.body.removeChild(elink)// 移除a标签
      loadingInstance.close();
    })
  }
};
export default ajax;
